package org.example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test1 {
    //leetcode 18 四数之和 https://leetcode.cn/problems/4sum/description/
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i < n-3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int j = i + 1;
            while (j < n-2) {
                long t = target - (long)nums[i] - nums[j];
                int left = j + 1, right = n - 1;
                if (t < 0 && nums[left] > 0) break;
                while (left < right) {
                    if (nums[left] + nums[right] < t) left++;
                    else if (nums[left] + nums[right] > t) right--;
                    else {
                        ret.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
                        while (left < right && nums[left] == nums[left + 1]) left++;
                        while (left < right && nums[right] == nums[right-1]) right--;
                        left++;
                        right--;
                    }
                }
                j++;
                while (j < n-2 && nums[j] == nums[j - 1]) j++;
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        Test1 test1 = new Test1();
        int[] arr = {1000000000,1000000000,1000000000,1000000000};
        test1.fourSum(arr,-294967296);
        System.out.println(666);
    }
}
